package 算法.leetcode.offer;

/**
 * @author lchenglong
 * @date 2022/4/20
 */
public class Offer67 {

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Long.MAX_VALUE);
        Offer67 instance = new Offer67();
        int ans = instance.strToInt("  0000000000012345678");
        System.out.println(ans);

    }
    public int strToInt(String str) {
        // 去掉空格
        str = str.trim();
        // 边界条件
        if (str.length()==0)return 0;
        // 取第一个字符
        char c = str.charAt(0);
        if (c == '-'||c == '+' || (c<='9'&&c>='0')){
            // 符合条件
            StringBuilder sb = new StringBuilder();
            int flag =1;
            for (int i=0;i<str.length();i++) {
                if (i==0&&str.charAt(i)=='-')flag= -1;
                else if (i==0&&str.charAt(i)=='+') continue;
                else if (str.charAt(i)<='9'&&str.charAt(i)>='0')sb.append(str.charAt(i));
                else break;
            }
            if (sb.length() == 0)return 0;
            // 转int
            long ans = 0;
            long b=1;
            int start=0;
            if (sb.charAt(0)=='0') {
                for (int i = 0; i < sb.length() - 1; i++) {
                    if(sb.charAt(i)=='0')start ++;
                    else break;
                }
            }
            for (int j=sb.length()-1;j>=start;j--){
                ans += (sb.charAt(j) -'0')*b;
                if (ans>Integer.MAX_VALUE){
                    break;
                }
                if (b > Integer.MAX_VALUE){
                    ans = Integer.MAX_VALUE;
                    break;
                }
                b=b*10;
            }
            if (ans>Integer.MAX_VALUE){
                if (flag ==-1)return Integer.MIN_VALUE;
                else return Integer.MAX_VALUE;
            } else {
                return (int) (ans * flag);
            }
        } else return 0;


    }
}
